/**
 *  (c)
 * <p>
 *
 * <p>
 *
 */

package com.nn.smart.bus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nn.smart.bus.commons.mybatis.service.impl.BaseServiceImpl;
import com.nn.smart.bus.commons.tools.constant.Constant;
import com.nn.smart.bus.commons.tools.constant.NumConstant;
import com.nn.smart.bus.commons.tools.page.PageData;
import com.nn.smart.bus.commons.tools.utils.ConvertUtils;
import com.nn.smart.bus.commons.tools.utils.Result;
import com.nn.smart.bus.dao.SysDictDao;
import com.nn.smart.bus.dto.SysDictDTO;
import com.nn.smart.bus.dto.SysSimpleDictDTO;
import com.nn.smart.bus.dto.epdc.form.SysPopulationSimpleDictFormDTO;
import com.nn.smart.bus.dto.epdc.result.EpdcAppSysDictResultDTO;
import com.nn.smart.bus.dto.epdc.result.SysPopulationSimpleDictDTO;
import com.nn.smart.bus.entity.SysDictEntity;
import com.nn.smart.bus.redis.SysDictRedis;
import com.nn.smart.bus.service.SysDictService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 数据字典
 *
 * @author nanning
 * @since 1.0.0
 */
@Slf4j
@Service
public class SysDictServiceImpl extends BaseServiceImpl<SysDictDao, SysDictEntity> implements SysDictService {

    @Autowired
    private SysDictRedis dictRedis;

    @Override
    public PageData<SysDictDTO> page(Map<String, Object> params) {

        IPage<SysDictEntity> page = baseDao.selectPage(
                getPage(params, "sort", true),
                getWrapper(params)
        );

        return getPageData(page, SysDictDTO.class);
    }

    @Override
    public List<SysDictDTO> subList(Map<String, Object> params) {
        List<SysDictEntity> entityList = baseDao.getSubList(params);
        return ConvertUtils.sourceToTarget(entityList, SysDictDTO.class);
    }

    @Override
    public List<SysDictDTO> list(Map<String, Object> params) {
        List<SysDictEntity> entityList = baseDao.selectList(getWrapper(params));

        return ConvertUtils.sourceToTarget(entityList, SysDictDTO.class);
    }

    private QueryWrapper<SysDictEntity> getWrapper(Map<String, Object> params) {
        String pid = (String) params.get("pid");
        String dictType = (String) params.get("dictType");
        String dictName = (String) params.get("dictName");
        String dictValue = (String) params.get("dictValue");

        QueryWrapper<SysDictEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(pid), "pid", Long.parseLong(pid));
        wrapper.eq(StringUtils.isNotBlank(dictType), "dict_type", dictType);
        wrapper.like(StringUtils.isNotBlank(dictName), "dict_name", dictName);
        wrapper.like(StringUtils.isNotBlank(dictValue), "dict_value", dictValue);

        return wrapper;
    }

    @Override
    public SysDictDTO get(Long id) {
        SysDictEntity entity = baseDao.selectById(id);

        return ConvertUtils.sourceToTarget(entity, SysDictDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysDictDTO dto) {
        SysDictEntity entity = ConvertUtils.sourceToTarget(dto, SysDictEntity.class);
        insert(entity);
        dictRedis.removeSimpleDictList(entity.getDictType());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysDictDTO dto) {
        SysDictEntity entity = ConvertUtils.sourceToTarget(dto, SysDictEntity.class);
        updateById(entity);
        dictRedis.removeSimpleDictList(entity.getDictType());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        //逻辑删除
        baseDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public void delete(Long id) {
        SysDictDTO dto = this.get(id);
        dictRedis.removeSimpleDictList(dto.getDictType());
        baseDao.deleteById(id);
    }

    @Override
    public Result<List<SysSimpleDictDTO>> listSimpleDictInfo(String dictType) {
        List<SysSimpleDictDTO> simpleDictList = Lists.newArrayList();

        try {
            if (StringUtils.isNotBlank(dictType)) {

                List<SysSimpleDictDTO> dictList = dictRedis.getSimpleDictList(dictType);
                if (null != dictList) {
                    return new Result<List<SysSimpleDictDTO>>().ok(dictList);
                }

                QueryWrapper<SysDictEntity> sdWrapper = new QueryWrapper<>();
                sdWrapper.select("dict_value", "dict_name","remark","id");
                sdWrapper.eq("dict_type", dictType);
                sdWrapper.ne("dict_value", "");
                sdWrapper.isNotNull("dict_value");
                sdWrapper.orderByAsc("SORT", Constant.CREATE_DATE);
                List<SysDictEntity> entityList = baseDao.selectList(sdWrapper);
                if (!entityList.isEmpty()) {
                    simpleDictList = ConvertUtils.sourceToTarget(entityList, SysSimpleDictDTO.class);
                    dictRedis.setSimpleDictList(dictType, simpleDictList);
                }
            }
        } catch (Exception e) {
            log.error("获取数据字典列表失败，错误信息{}", e.getMessage());
        }
        return new Result<List<SysSimpleDictDTO>>().ok(simpleDictList);
    }

    @Override
    public Result<List<EpdcAppSysDictResultDTO>> listFullDictInfo(String dictType) {
        List<EpdcAppSysDictResultDTO> fullDictList = Lists.newArrayList();

        try {
            if (StringUtils.isNotBlank(dictType)) {

                List<EpdcAppSysDictResultDTO> dictList = dictRedis.getFullDictList(dictType);
                if (null != dictList) {
                    return new Result<List<EpdcAppSysDictResultDTO>>().ok(dictList);
                }

                QueryWrapper<SysDictEntity> sdWrapper = new QueryWrapper<>();
                sdWrapper.select("id", "pid", "dict_type", "dict_value", "dict_name", "remark", "sort");
                sdWrapper.eq("dict_type", dictType);
                sdWrapper.eq(Constant.DEL_FLAG, NumConstant.ZERO);
                sdWrapper.ne("dict_value", "");
                sdWrapper.isNotNull("dict_value");
                sdWrapper.orderByAsc("SORT", Constant.CREATE_DATE);
                List<SysDictEntity> entityList = baseDao.selectList(sdWrapper);
                if (!entityList.isEmpty()) {
                    fullDictList = ConvertUtils.sourceToTarget(entityList, EpdcAppSysDictResultDTO.class);
                    dictRedis.setFullDictList(dictType, fullDictList);
                }
            }
        } catch (Exception e) {
            log.error("获取数据字典列表失败，错误信息{}", e.getMessage());
        }
        return new Result<List<EpdcAppSysDictResultDTO>>().ok(fullDictList);
    }
    @Override
    public Result<List<SysPopulationSimpleDictDTO>> listPopulationSimple(SysPopulationSimpleDictFormDTO sysPopulationSimpleDictFormDTO) {
        List<SysPopulationSimpleDictDTO> sysPopulationSimpleDictDTOS = new ArrayList<>();
        try {
            for(String dictType : sysPopulationSimpleDictFormDTO.getDicTypes()){
                SysPopulationSimpleDictDTO sysPopulationSimpleDictDTO = new SysPopulationSimpleDictDTO();
                List<SysSimpleDictDTO> simpleDictList = Lists.newArrayList();

                if (StringUtils.isNotBlank(dictType)) {
                    List<SysSimpleDictDTO> dictList = dictRedis.getSimpleDictList(dictType);
                    if (null != dictList) {
                        sysPopulationSimpleDictDTO.setSysSimpleDicts(dictList);
                        sysPopulationSimpleDictDTO.setDicType(dictType);
                        sysPopulationSimpleDictDTOS.add(sysPopulationSimpleDictDTO);
                        continue;
                    }

                    QueryWrapper<SysDictEntity> sdWrapper = new QueryWrapper<>();
                    sdWrapper.select("dict_value", "dict_name");
                    sdWrapper.eq("dict_type", dictType);
                    sdWrapper.ne("dict_value", "");
                    sdWrapper.isNotNull("dict_value");
                    sdWrapper.orderByAsc("SORT", Constant.CREATE_DATE);
                    List<SysDictEntity> entityList = baseDao.selectList(sdWrapper);
                    if (!entityList.isEmpty()) {
                        simpleDictList = ConvertUtils.sourceToTarget(entityList, SysSimpleDictDTO.class);
                        sysPopulationSimpleDictDTO.setSysSimpleDicts(simpleDictList);
                        sysPopulationSimpleDictDTO.setDicType(dictType);
                        sysPopulationSimpleDictDTOS.add(sysPopulationSimpleDictDTO);
                        dictRedis.setSimpleDictList(dictType, simpleDictList);
                    }
                }
            }

        } catch (Exception e) {
            log.error("获取数据字典列表失败，错误信息{}", e.getMessage());
        }
        return new Result<List<SysPopulationSimpleDictDTO>>().ok(sysPopulationSimpleDictDTOS);
    }
}
